#include <FS.h> //ESP设备内置FileSystem,可操作FLASH
#include <ArduinoJson.h>
#include <ESP8266WiFi.h> //可创建WIFI热点
#include <WiFi.h>
#include "fetchinfo.h"
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Wifi
const char *ssid = "Super Puppy";
const char *password = "";
const char *SSIDFile = "/ssid.json";
void WiFiEvent(WiFiEvent_t event);
void WifiConfig(DynamicJsonDocument &doc) {
    fs::File file = SPIFFS.open(SSIDFile, "w");
    if(file) {
      serializeJson(doc,file);
      file.close();
    }
}
void StartWifiAP() {
    WiFi.softAP(ssid, password);
}
void LoadWifiConfig() {
  if(SPIFFS.begin()) {
    fs::File file = SPIFFS.open(SSIDFile, "r");
    if (file) {
      DynamicJsonDocument doc(1024);
      DeserializationError err =  deserializeJson(doc,file);
      if(!err) {
        String ssid = doc["ssid"];
        String passwd = doc["password"];
        String wapi = doc["weather-api"];
        String city = doc["city"];
        Serial.println(ssid);
        Serial.println(passwd);
        Serial.println(wapi);
        InfoConfig(city,wapi);
        WiFi.onEvent(WiFiEvent);
        WiFi.begin(ssid, passwd);
        unsigned long startAttempt = millis();
        Serial.println("Try to connect WiFi");
        while(WiFi.status() != WL_CONNECTED) {
          delay(500);
          if(millis() - startAttempt > 5000) {
            break;
          }
        }
      } else {
        printf("Failed to read file");
        return;
      }
      if(WiFi.status() != WL_CONNECTED) {
        //HandleWifiConfig();
        Serial.println("WiFi not connected");
      } else {
        Serial.println("WiFi connected");
      }
    } else {
      Serial.println("File not ready");
    }
  } else {
    Serial.println("SPIFFS not ready");
  }
}

int maxRetries = 3;
int retryCount = 0;
void WiFiEvent(WiFiEvent_t event) {
  switch (event) {
    case WIFI_EVENT_STAMODE_CONNECTED:
      retryCount = 0;
      break;
    case WIFI_EVENT_STAMODE_DISCONNECTED:
      Serial.println("WiFi connection lost");
      if (retryCount < maxRetries) {
        Serial.println("Attempting to reconnect...");
        WiFi.reconnect();
        retryCount++;
      } else {
        Serial.println("Max retries reached. Restarting ESP32...");
        ESP.restart();
      }
      break;
      
    default:
      break;
  }
}